/// <reference path="Application_koViewModel.g.js" />
/// <reference path="../Scripts/jquery-1.7.1.min.js" />
/// <reference path="../Scripts/knockout-2.1.0.js" />

function ApplicationViewModel() {
    var self = this;
    // put a property loop here
    self.ApplicationID = ko.observable();
    self.ApplicationName = ko.observable();
    self.TS = ko.observable();
    self.CreatedBy = ko.observable();
    self.CreatedDt = ko.observable();
    self.ModifiedBy = ko.observable();
    self.ModifiedDt = ko.observable();
    self.Action = ko.observable();
    self.Caller = ko.observable();
    self.Role = ko.observable();
    self.PageSize = ko.observable();
    self.PageNumber = ko.observable();
    self.SortColumn = ko.observable();
    self.SortType = ko.observable();
    self.TotalRows = ko.observable();

    self.myBoolean = ko.observable();
    self.LoadingApplication = ko.observable();
    self.EditingApplication = ko.observable();
    self.sortRecords = ko.observableArray();

    
    self.ApplicationList = ko.observableArray([]);
    self.setApplication = function (
			_ApplicationID, _ApplicationName, _TS, _CreatedBy, _CreatedDt, _ModifiedBy, _ModifiedDt, _Action, _Caller, _Role, _PageNumber, _PageSize, _SortColumn, _SortType, _TotalRows

	) {

        self.ApplicationID = _ApplicationID;
        self.ApplicationName = _ApplicationName;
        self.TS = _TS;
        self.CreatedBy = _CreatedBy;
        self.CreatedDt = _CreatedDt;
        self.ModifiedBy = _ModifiedBy;
        self.ModifiedDt = _ModifiedDt;
        self.Action = _Action;
        self.Caller = _Caller;
        self.Role = _Role;
        self.PageSize = _PageSize
        self.PageNumber = _PageNumber;
        self.SortColumn = _SortColumn;
        self.SortType = _SortType;
        self.TotalRows = _TotalRows;

    }; //  End of set procedure 

    //Add Application
    self.AddApplication = function () {
        var self = this;
        self.Action = "Add";
        self.Caller = "trooks";
        self.Role = "user";
        
        $(".form").validate({ rules: { txtApplicationName: { required: true } } });
        if (!$(".form").valid()) {
            //alert("Invalied");
            return;
        }
        jQuery.ajax({
            url: "./api/ApplicationAPI/",
            data: ko.toJSON({ ApplicationName: self.ApplicationName, Action: self.Action, Caller: self.Caller }),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                //alert(result);
                $('#myModaladd').modal('hide');
                self.GetApplicationByParameter();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                $('#error-dis').text(thrownError);
                $('#register-error').css({ 'display': 'block' });
                $('#SearchFilter-home').css({ 'display': 'none' });
                $('#myModaladd').modal('hide');
                $(document).scrollTop(0);
            }
        });
        $(".form")[0].reset();
    }; 
       
    self.LoadApplication = function (appVal) {
        self.LoadingApplication(appVal);
    };
       
    //Delete Application
    self.DeleteApplicationAction = function (appval) {
        self.Action = "Remove";
        self.Caller = "trooks";
        
        jQuery.ajax({
            url: "./api/ApplicationApi/",
            data: ko.toJSON({ Action: self.Action, Caller: self.Caller, ApplicationID: appval.ApplicationID, TS: appval.TS }),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                $('#myModal').modal('hide');                                
                self.GetApplicationByParameter();                
            },
            error: function (xhr, ajaxOptions, thrownError) {
            $('#error-dis').text(thrownError);
            $('#register-error').css({ 'display': 'block' });
            $('#SearchFilter-home').css({ 'display': 'none' });
            $('#myModal').modal('hide');
            $(document).scrollTop(0);
        }
        });        
    };
    //Edit Application

    self.EditApplication = function (appVal) {
        self.EditingApplication(appVal);
    };  

    self.UpdateApplication = function (appval) {
        self.Action = "Update";
        self.Caller = "trooks";
        self.Role = "user";
        
        $(".form1").validate({ rules: { txtApplicationName: { required: true } } });
        if (!$(".form1").valid()) {
            return;
        }
        jQuery.ajax({
            url: "./api/ApplicationAPI/",
            data: ko.toJSON({ ApplicationName: appval.ApplicationName, Action: self.Action, Caller: self.Caller, ApplicationID: appval.ApplicationID, TS: appval.TS, CreatedBy: appval.CreatedBy, CreatedDt: appval.CreatedDt, ModifiedBy: appval.ModifiedBy, ModifiedDt: appval.ModifiedDt }),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (result) {                
                $('#myModalEdit').modal('hide');
                self.GetApplicationByParameter();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                $('#error-dis').text(thrownError);
                $('#register-error').css({ 'display': 'block' });
                $('#SearchFilter-home').css({ 'display': 'none' });
                $('#myModalEdit').modal('hide');
                $(document).scrollTop(0);
            }

        });

        

    }; 
 

    ko.bindingHandlers.sort = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var asc = false;
            element.style.cursor = 'pointer';

            element.onclick = function () {
                var value = valueAccessor();
                var prop = value.prop;
                var data = value.arr;

                asc = !asc;
                if (asc) {
                    self.ApplicationList.sort(function (left, right) {
                        return left[prop] == right[prop] ? 0 : left[prop] < right[prop] ? -1 : 1;
                    });
                } else {
                    self.ApplicationList.sort(function (left, right) {
                        return left[prop] == right[prop] ? 0 : left[prop] > right[prop] ? -1 : 1;
                    });
                }
            }
        }
    };

//loading model popup
    ko.bindingHandlers['modal'] = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var allBindings = allBindingsAccessor();
            var $element = $(element);
            $element.addClass('hide modal');

            if (allBindings.modalOptions) {
                if (allBindings.modalOptions.beforeClose) {
                    $element.on('hide', function () {
                        return allBindings.modalOptions.beforeClose();
                    });
                }
            }

            return ko.bindingHandlers['with'].init.apply(this, arguments);
        },
        update: function (element, valueAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor());

            var returnValue = ko.bindingHandlers['with'].update.apply(this, arguments);

            if (value) {
                $(element).modal('show');
            } else {
                $(element).modal('hide');
            }

            return returnValue;
        }
    };

    //filter

    self.ApplicationList = ko.observableArray([]);
    self.filter = ko.observable("");
    
    self.filteredApplication = ko.computed(function () {
        var filterText = self.filter().toLowerCase();
        return ko.utils.arrayFilter(self.ApplicationList(), function (item) {
            return filterText.length < 1 || item.ApplicationID == filterText || item.CreatedBy == filterText || item.ModifiedBy == filterText || item.ApplicationName.toLowerCase().indexOf(filterText) != -1
        });

    }, self);

    self.GetApplicationByParameter = function () {
        self.Action = "GetAll";
        self.Caller = "trooks";
        self.Role = "user";
        self.PageNumber = 1;
        self.PageSize = 10;
        self.SortColumn = "ApplicationID";
        self.SortType = "asc";
        jQuery.ajax({
            url: "./api/ApplicationAPI/",
            data: { Action: self.Action, Caller: self.Caller, Role: self.Role, PageNumber: self.PageNumber, PageSize: self.PageSize, SortColumn: self.SortColumn, SortType: self.SortType },
            type: 'GET',
            success: function (result) {
                self.ApplicationList.removeAll();
                $.each(result, function (key, val) {
                    self.ApplicationList.push(
                        val
                    )
                })
            },
            error: function (xhr, ajaxOptions, thrownError) {
                $('#error-dis').text(thrownError);
                $('#register-error').css({ 'display': 'block' });
                $('#SearchFilter-home').css({ 'display': 'none' });                
                $(document).scrollTop(0);
            }
        });
        
        if (loginUserRole.indexOf('super admin') <= -1) {
            $('.add-btn').attr('disabled', 'disabled');
        }
    };

    ko.bindingHandlers.jqAuto = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var options = valueAccessor() || {};
            var allBindings = allBindingsAccessor();
            var unwrap = ko.utils.unwrapObservable;

            //handle value changing
            var modelValue = allBindings.jqAutoValue;
            if (modelValue) {
                var handleValueChange = function (event, ui) {
                    var valueToWrite = ui.item ? ui.item.value : $(element).val();
                    if (ko.isWriteableObservable(modelValue)) {
                        modelValue(valueToWrite);

                    } else {  //write to non-observable
                        if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers']['jqAutoValue'])
                            allBindings['_ko_property_writers']['jqAutoValue'](valueToWrite);
                    }
                };

                options.change = handleValueChange;
                options.select = handleValueChange;
            }

            //handle the choices being updated in a DO, so the update function doesn't have to do it each time the value is updated
            var mappedSource = ko.dependentObservable(function () {
                var source = unwrap(allBindings.jqAutoSource);
                var valueProp = unwrap(allBindings.jqAutoSourceValue);
                var labelProp = unwrap(allBindings.jqAutoSourceLabel) || valueProp;

                var mapped = ko.utils.arrayMap(source, function (item) {
                    var result = {};
                    result.label = labelProp ? unwrap(item[labelProp]) : unwrap(item).toString();  //show in pop-up choices
                    result.value = valueProp ? unwrap(item[valueProp]) : unwrap(item).toString();  //value 
                    return result;
                });
                return mapped;
            });

            mappedSource.subscribe(function (newValue) {
                $(element).autocomplete("option", "source", newValue);
            });

            options.source = mappedSource();

            $(element).autocomplete(options);
        },
        update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            //update value based on a model change
            var allBindings = allBindingsAccessor();
            var modelValue = allBindings.jqAutoValue;
            if (modelValue) {
                $(element).val(ko.utils.unwrapObservable(modelValue));
            }
        }
    };

    self.myOptions = ko.observableArray([]),
    mySelectedOption = ko.observable();
    function Item(id, name) {
        //var self = this;        
        return {
            id: ko.observable(id),
            name: ko.observable(name)
        };
    }

    ko.bindingHandlers.bootstrapPopover = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var options = valueAccessor();
            var defaultOptions = { trigger: 'hover' };
            options = $.extend(true, {}, defaultOptions, options);
            $(element).popover(options);
        }
    };

}; //End of view model








